<template>
  <view class="container">
    <!-- 顶部搜索栏 -->
    <view class="fixed-header">
      <view class="nav-bar">
        <view class="search-bar">
          <view class="search-box">
            <text class="icon-search">🔍</text>
            <input 
              class="search-input" 
              placeholder="搜索职位、公司" 
              placeholder-style="color:#999;"
              v-model="searchKeyword"
              @confirm="handleConfirm" 
            />
          </view>
          <text class="search-btn" @click="performSearch">搜索</text>
          <text class="cancel-btn" @click="goBack">取消</text>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view 
      class="content-area" 
      scroll-y
      :style="{ height: contentHeight + 'px' }"
      @scrolltolower="loadMore"
    >
      <!-- 无结果提示 -->
      <view class="empty-state" v-if="jobList.length === 0 && !loading">
        <image class="empty-icon" src="/static/empty.png" mode="aspectFit"></image>
        <text class="empty-text">没有找到符合条件的职位</text>
      </view>
      
      <!-- 职位列表 -->
      <view 
        class="job-item" 
        v-for="(job, index) in jobList" 
        :key="index"
        @click="goRecruitmentDetails(job)"
      >
        <view class="job-header">
          <view class="job-title">{{ job.jobName }}</view>
          <view class="salary">{{ setSalary(job.startSalary, job.maxSalary, job.payMethod) }}</view>
        </view>
        <view class="company">{{ job.companyName }}</view>
        <view class="requirements">
          <text v-for="(req, idx) in splitRequirements(job.skillRequest)" :key="idx" class="requirement-tag">
            {{ req }}
          </text>
        </view>
        <view class="contact">
          <text>◯ {{ job.hrName }}</text>
          <text>{{ job.identity === 0 ? 'hr主管' : 'hr' }}</text>
          <text>{{ job.parentName }} - {{ job.childName }}</text>
        </view>
      </view>
      
      <!-- 底部状态提示 -->
      <view class="load-more" v-if="loading && jobList.length > 0">加载中...</view>
      <view class="no-more" v-if="!loading && jobList.length > 0 && hasNoMore">没有了</view>
    </scroll-view>
  </view>
</template>

<script>
import http from '../../utils/request';
import state from '../../store/state';
import { search } from '@/api/user.js'; // 导入搜索接口

export default {
  data() {
    return {
      searchKeyword: '',
      loading: false,
      jobList: [],
      pageNum: 1,
      pageSize: 5,
      totalCount: 0,
      hasNoMore: false,
      contentHeight: 0
    };
  },
  onReady() {
    this.calcContentHeight();
  },
  methods: {
    // 计算内容区域高度
    calcContentHeight() {
      const query = uni.createSelectorQuery().in(this);
      query.select('.fixed-header').boundingClientRect(data => {
        const systemInfo = uni.getSystemInfoSync();
        this.contentHeight = systemInfo.windowHeight - data.height;
      }).exec();
    },

    // 执行搜索
    performSearch() {
      if (!this.searchKeyword.trim()) {
        uni.showToast({ title: '请输入搜索关键词', icon: 'none' });
        return;
      }
      
      // 重置分页参数，重新搜索
      this.pageNum = 1;
      this.jobList = [];
      this.loading = true;
      this.hasNoMore = false;
      
      this.fetchSearchData();
    },

    // 处理回车事件
    handleConfirm() {
      this.performSearch();
    },

    // 调用搜索接口
    fetchSearchData() {
      search({
        searchKeyword: this.searchKeyword,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(res => {
        if (res.code === 200) {
          const newList = res.data.list || [];
          // 分页数据拼接
          this.jobList = this.pageNum === 1 ? newList : [...this.jobList, ...newList];
          this.totalCount = res.data.total || 0;
          this.checkHasNoMore();
        } else {
          uni.showToast({ title: res.msg || '搜索失败', icon: 'none' });
        }
      }).catch(err => {
        console.error('搜索接口异常:', err);
        uni.showToast({ title: '网络错误', icon: 'none' });
      }).finally(() => {
        this.loading = false;
      });
    },

    // 加载更多
    loadMore() {
      if (this.loading || this.hasNoMore) return;
      
      this.pageNum++;
      this.loading = true;
      this.fetchSearchData();
    },

    // 检查是否已加载全部
    checkHasNoMore() {
      this.hasNoMore = this.jobList.length >= this.totalCount;
    },

    // 薪资格式化
    setSalary(startSalary, maxSalary, payMethod) {
      if (payMethod === 4) return '面议';
      
      const units = ['/日', '/周', '/月', '/时'];
      const unit = units[payMethod] || '';
      
      if (maxSalary === null) return `${startSalary}${unit} 起`;
      if (startSalary === null) return `最高 ${maxSalary}${unit}`;
      return `${startSalary} ~ ${maxSalary}${unit}`;
    },

    // 分割技能要求
    splitRequirements(text) {
      return text ? text.split(',').slice(0, 3) : [];
    },

    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 跳转到职位详情
    goRecruitmentDetails(job) {
      uni.navigateTo({ 
        url: `/pages/zcy/recruitmentDetails?recruitId=${job.recruitId}&userId=${state.userInfo?.userId || ''}` 
      });
    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
  position: relative;
}

/* 顶部固定区域 */
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #fff;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.nav-bar {
  padding: 10px 15px;
  height: 50px;
  border-bottom: 1px solid #f0f0f0;
}

.search-bar {
  display: flex;
  align-items: center;
  height: 100%;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background: #f0f2f5;
  border-radius: 20px;
  padding: 8px 15px;
}

.icon-search {
  margin-right: 8px;
  font-size: 18px;
  color: #999;
}

.search-input {
  flex: 1;
  height: 32px;
  font-size: 16px;
  color: #333;
  background: transparent;
}

.search-btn {
  margin-left: 12px;
  margin-right: 8px;
  color: #1890ff;
  font-size: 16px;
  padding: 5px 8px;
}

.cancel-btn {
  margin-left: 8px;
  color: #1890ff;
  font-size: 16px;
  padding: 5px 8px;
}

/* 内容区域 */
.content-area {
  width: 100%;
  padding: 10px 15px;
  margin-top: 50px; /* 与顶部导航栏高度一致 */
  overflow: hidden;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.empty-icon {
  width: 100px;
  height: 100px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  color: #999;
}

/* 职位列表样式 */
.job-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.job-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.salary {
  margin-right: 30px;
  font-size: 14px;
  color: #ff6b6b;
  font-weight: bold;
}

.company {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.requirements {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 8px;
}

.requirement-tag {
  font-size: 12px;
  color: #999;
  margin-right: 8px;
  margin-bottom: 5px;
  padding: 3px 8px;
  background-color: #f5f5f5;
  border-radius: 12px;
  display: inline-block;
}

.contact {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.contact text {
  margin-right: 10px;
}

.contact text:first-child {
  color: #1890ff;
}

/* 加载状态样式 */
.load-more {
  text-align: center;
  padding: 20rpx;
  font-size: 14px;
  color: #999;
}

.no-more {
  text-align: center;
  padding: 20rpx;
  font-size: 14px;
  color: #ccc;
}
</style>